<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref, nextTick, getCurrentInstance } from 'vue'
	import { getFoodCategorize, getFoodGoods, addShopCarArray } from '@/api/shop'
	import { useUserStore } from '@/store/user'
	const instance = getCurrentInstance().proxy
	
	const user = useUserStore()
	const statusHeight = ref(0)
	const menuHeight = ref(32)
	const menuWidth = ref(0)
	const contHeight = ref(66)
	const loading = ref(false)
	const navTopList = ref([])
	const navTopCurrent = ref(-1)
	const navTopLeft = ref(0)
	const showMore = ref(false)
	const morePopup = ref(null)
	const navLeftList = ref([])
	const navLeftCurrent = ref(-1)
	const curCurrent = ref(0)
	let LeftPos = []
	const indexLoading = ref(-1)
	const totalPrice = ref(0)
	
	function backPage() {
		uni.navigateBack({
			fail: () => {
				uni.switchTab({url: '/pages/tabbar/index'})
			}
		})
	}
	function search() {
		uni.navigateTo({url: '/pages/search'})
	}
	function handleNavTop(index) {
		if(index != navTopCurrent.value) {
			navTopCurrent.value = index
			navTopLeft.value = index > 0 ? (index - 1) * 90 : 0
			let curTop = navTopList.value[index]
			navLeftCurrent.value = -1
			LeftPos = []
			navLeftList.value = []
			nextTick(() => {
				navLeftList.value = curTop.children || []
				if(navLeftList.value.length) handleNavLeft(0)
			})
			morePopupClose()
		}
	}
	function handleNavLeft(index, scroll = false) {
		if(index != navLeftCurrent.value) {
			navLeftCurrent.value = index
			if(!scroll) curCurrent.value = index
			getData(index, () => {
				getData(index + 1)
			})
		}
	}
	function getData(index, next) {
		let curLeft = navLeftList.value[index]
		if(curLeft && !curLeft.foodList) {
			let goodsType = curLeft.typeId
			curLeft.foodList = []
			indexLoading.value = index
			getFoodGoods({goodsType, areaId: user.addressIds[2], status: 1}).then(res => {
				let result = res.result || []
				result.forEach(item => {
					if(!item.num) item.num = 0
				})
				curLeft.foodList = result
				indexLoading.value = -1
				next && next()
			}).catch(() => {
				indexLoading.value = -1
				next && next()
			})
		} else {
			next && next()
		}
	}
	function numChange() {
		const goodsList = dealGoods()
		let total = goodsList.reduce((total, item) => {
			total += item.number * 1000 * item.price
			return total
		}, 0)
		totalPrice.value = total / 1000
	}
	function getCategorize() {
		loading.value = true
		getFoodCategorize().then(res => {
			let result = res.result || []
			navTopList.value = result
			if(result.length) handleNavTop(0)
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function addCar() {
		if(loading.value || navTopCurrent.value === -1) return
		const goodsList = dealGoods()
		if(!goodsList.length) {
			uni.showToast({icon: 'none', title: '请选择食材'})
			return
		}
		loading.value = true
		let data = goodsList.map(item => {
			return {
				goodsId: item.id,
				type: 'INGREDIENT',
				num: item.number
			}
		})
		addShopCarArray(data).then(res => {
			uni.showToast({icon: 'success', title: '添加成功'})
			user.shopCarAction(false)
			clearCurData()
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function goBuy() {
		if(loading.value || navTopCurrent.value === -1) return
		const goodsList = dealGoods()
		if(!goodsList.length) {
			uni.showToast({icon: 'none', title: '请选择食材'})
			return
		}
		loading.value = true
		let data = {
			total: totalPrice.value,
			list: goodsList
		}
		uni.navigateTo({
			url: '/pages/shop/orderConfirm',
			success: res => {
				res.eventChannel.emit('orderConfirm', data)
			}
		})
		loading.value = false
	}
	function dealGoods() {
		let children = []
		navTopList.value.forEach(navTop => {
			navTop.children.forEach(navLeft => {
				if(navLeft.foodList) {
					navLeft.foodList.forEach(food => {
						if(food.num) {
							children.push({
								id: food.goodsId,
								name: food.goodsName,
								furl: food.images && food.images[0] && food.images[0].furl || '',
								price: food.price,
								specs: food.specs,
								number: food.num,
								type: 'INGREDIENT'
							})
						}
					})
				}
			})
		})
		return children
	}
	function clearCurData() {
		navTopList.value.forEach(navTop => {
			navTop.children.forEach(navLeft => {
				if(navLeft.foodList) {
					navLeft.foodList.forEach(food => {
						food.num = 0
					})
				}
			})
		})
		totalPrice.value = 0
	}
	function openPage(item) {
		let url = `/pages/shop/goodsDetail?id=${item.goodsId}&title=${item.goodsName}`
		uni.navigateTo({url})
	}
	function goCar() {
		uni.switchTab({url: '/pages/tabbar/shop'})
	}
	function handleMore() {
		if(showMore.value) {
			morePopup.value.close()
		} else {
			morePopup.value.open('top')
		}
	}
	function morePopupChange(e) {
		showMore.value = e.show
	}
	function morePopupClose() {
		if(showMore.value) {
			morePopup.value.close()
		}
	}
	function goodsScroll(e) {
		let scrollTop = e.detail.scrollTop
		let leftListLength = navLeftList.value.length
		let tabHeight = 0
		for (let i = 0; i < leftListLength; i++) {
			let view = uni.createSelectorQuery().in(instance).select("#main-" + i)
			view.fields({size: true}, data => {
				LeftPos[i] = {top: tabHeight}
				tabHeight = tabHeight + data.height
			}).exec()
		}
		setTimeout(() => {
			let curSection = LeftPos.findIndex(item => scrollTop + 6 < item.top)
			let index = curSection !== -1 ? curSection : LeftPos.length
			index = index > 0? index - 1 : index
			handleNavLeft(index, true)
		}, 100)
	}
	
	onLoad(() => {
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		statusHeight.value = menuButtonInfo.top
		menuHeight.value = menuButtonInfo.height
		menuWidth.value = menuButtonInfo.left
		contHeight.value = menuButtonInfo.bottom + 10
		// #endif
		getCategorize()
	})
</script>

<template>
	<view class="app-container">
		<view class="nav-head" :style="{height: contHeight + 'px'}">
			<view class="status-menuButton" :style="{ height: statusHeight + 'px' }"></view>
			<view class="nav-box" :style="{height: menuHeight + 'px', width: menuWidth? menuWidth + 'px' : '100%'}">
				<view class="nav-title" @click="backPage">
					<uv-icon name="arrow-left" color="#000000" size="40" bold />
					<text>食材直供</text>
				</view>
				<view class="search-box theme-btn" @click="search">
					<uv-icon name="search" color="#5B5B5B" size="40" />
					<input type="text" placeholder="输入搜索的商品" disabled class='input-text' />
				</view>
			</view>
		</view>
		<view class="nav-content" :style="{height: 'calc(100% - ' + contHeight + 'px )'}" v-if="navTopList.length">
			<view class="app-head">
				<scroll-view scroll-x="true" :class="['nav-top', navTopList.length > 5? 'more-show' : '']" :scroll-left="navTopLeft" scroll-with-animation='true'>
					<view :class="['head-item', navTopCurrent == index? 'active' : '']" v-for="(nav, index) in navTopList" :key="nav.typeId" 
						@click="handleNavTop(index)">
						<view class="head-box">
							<view class="head-image"><uv-image :src="nav.images && nav.images[0] && nav.images[0].furl" width="100%" height="100%"></uv-image></view>
							<view class="head-title uv-line-1">{{nav.typeName}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="nav-more" @click="handleMore" v-if="navTopList.length > 5">
					<text class="more-text">{{ showMore? '收起' : '展开'}}</text>
					<uv-icon :name="showMore? 'arrow-up-fill' : 'arrow-down-fill'" color="#4E5969" size="24"></uv-icon>
				</view>
			</view>
			<view class="app-content">
				<scroll-view scroll-y="true" class="content-left" v-if="navLeftList.length">
					<view :class="['left-item', navLeftCurrent == index? 'active' : '']" v-for="(nav, index) in navLeftList" :key="nav.typeId"
						@click="handleNavLeft(index)">
						{{nav.typeName}}
					</view>
				</scroll-view>
				<scroll-view scroll-y="true" scroll-with-animation :scroll-into-view="'main-'+ curCurrent" class="content-right" @scroll="goodsScroll">
					<template v-if="navLeftList.length">
						<view :class="['right-list', nav.foodList? '' : 'full-height']" v-for="(nav, index) in navLeftList" :key="nav.typeId" :id="'main-'+index">
							<uv-sticky offset-top="0">
								<view class="good-title">{{nav.typeName}}</view>
							</uv-sticky>
							<view v-for="item in nav.foodList" :key="item.goodsId" class="good-box" @click="openPage(item)">
								<goods v-model="item.num" :img="item.images && item.images[0] && item.images[0].furl" :name="item.goodsName" :price="item.price" 
									:linePrice="item.linePrice" :specs="item.specs" :min="item.minNum" :max="item.maxNum" @change="numChange"></goods>
							</view>
							<uv-load-more status="loading" fontSize="28" iconSize="34" marginTop="80" v-if="indexLoading === index"></uv-load-more>
						</view>
					</template>
					<empty text="没有找到分类下的商品" v-else></empty>
				</scroll-view>
			</view>
			<view class="app-bottom">
				<shopBar :carNum="user.shopCar.length" :totalPrice="totalPrice" :loading="loading || navTopCurrent === -1" @car="goCar" @add="addCar" @buy="goBuy"
					:buyDisabled="totalPrice < 1000"></shopBar>
			</view>
		</view>
		<uv-popup ref="morePopup" round="32" :safeAreaInsetTop="true" :safeAreaInsetBottom="false" @change="morePopupChange">
			<view class="more-name">所有分类</view>
			<view class="more-list">
				<view :class="['more-item', navTopCurrent == index? 'active' : '']" v-for="(nav, index) in navTopList" :key="nav.typeId" @click="handleNavTop(index)">
					<view class="more-image"><uv-image :src="nav.images && nav.images[0] && nav.images[0].furl" width="100%" height="100%"></uv-image></view>
					<view class="more-title uv-line-1">{{nav.typeName}}</view>
				</view>
			</view>
			<view class="more-bottom" @click="morePopupClose">
				<text>收起</text>
				<uv-icon name="arrow-up-fill" color="#4E5969" size="24"></uv-icon>
			</view>
		</uv-popup>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		height: 100vh;
		.nav-head {
			background-color: white;
			border: 2px solid #FAF7F7;
			.nav-box{
				padding: 0 16rpx 0 10rpx;
				display: flex;
				align-items: center;
				gap: 36rpx;
				.nav-title{
					flex-shrink: 0;
					font-weight: 600;
					font-size: 36rpx;
					display: flex;
					align-items: center;
				}
				.search-box{
					flex: 1;
					height: 100%;
					padding: 12rpx;
					display: flex;
					align-items: center;
					gap: 6rpx;
					background-color: #F5F5F5;
					border-radius: 72rpx;
					.input-text{
						flex: 1;
					}
				}
			}
		}
		.app-head{
			height: 196rpx;
			background-color: #FFFFFF;
			display: flex;
			.nav-top{
				width: 100%;
				height: 196rpx;
				padding-left: 22rpx;
				white-space: nowrap;
				&.more-show{
					width: calc(100% - 80rpx);
				}
			}
			.nav-more{
				width: 80rpx;
				height: 196rpx;
				box-shadow: -8rpx 0rpx 16rpx 0rpx rgba(0,0,0,0.08);
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				gap: 20rpx;
				.more-text{
					writing-mode: vertical-rl;
				}
			}
			.head-item{
				display: inline-block;
				width: 124rpx;
				height: 100%;
				padding: 22rpx 0;
				margin-right: 22rpx;
				.head-box{
					width: 100%;
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					align-items: center;
					.head-image{
						width: 104rpx;
						height: 104rpx;
						border-radius: 36rpx;
						border: 6rpx solid transparent;
						overflow: hidden;
					}
					.head-title{
						padding: 0 8rpx;
						border-radius: 36rpx;
						font-size: var(--theme-sm);
						line-height: var(--theme-sm-line);
					}
				}
				&.active{
					.head-image{
						border-color: rgba(250,63,0,0.8);
					}	
					.head-title{
						font-weight: 600;
						color: #FFFFFF;
						background-color: #FA3F00;
					}
				}
			}
		}
		.app-content{
			margin-top: 16rpx;
			height: calc(100% - 324rpx);
			display: flex;
			.content-left{
				flex-shrink: 0;
				width: 180rpx;
				height: 100%;
				.left-item{
					padding: 32rpx 16rpx;
					text-align: center;
					position: relative;
					color: #333333;
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
					&.active{
						font-weight: 600;
						background-color: #FFFFFF;
						color: #FD1024;
						&::before{
							content: '';
							position: absolute;
							left: 0rpx;
							top: 20rpx;
							bottom: 20rpx;
							width: 6rpx;
							background-color: #FA3F00;
							border-radius: 0 6rpx 6rpx 0;
							z-index: 10;
						}
					}
				}
			}
			.content-right{
				flex: 1;
				height: 100%;
				background-color: #FFFFFF;
				padding: 0 16rpx;
				.right-list{
					min-height: 280rpx;
					&:last-child{
						min-height: 100%;
					}
					&.full-height{
						min-height: 100%;
					}
					.good-title{
						padding-top: 24rpx;
						margin-bottom: -8rpx;
						font-weight: 600;
						background-color: #FFFFFF;
					}
					.good-box{
						padding: 32rpx 0;
						border-bottom: 2rpx solid #F4F4F4;
					}
				}
			}
		}
		.app-bottom{
			border-top: 1rpx solid #D7DBE1;
			height: 112rpx;
		}
		.more-name{
			padding: 22rpx 0 0 22rpx;
			font-weight: 600;
			font-size: var(--theme-lg);
			line-height: var(--theme-lg-line);
		}
		.more-list{
			padding: 20rpx;
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx  20rpx;
			.more-item{
				width: 124rpx;
				height: 152rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				.more-image{
					width: 104rpx;
					height: 104rpx;
					border-radius: 36rpx;
					border: 6rpx solid transparent;
					overflow: hidden;
				}
				.more-title{
					padding: 0 8rpx;
					border-radius: 36rpx;
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
				}
				&.active{
					.more-image{
						border-color: rgba(250,63,0,0.8);
					}	
					.more-title{
						font-weight: 600;
						color: #FFFFFF;
						background-color: #FA3F00;
					}
				}
			}
		}
		.more-bottom{
			border-top: 2rpx solid #D7DBE1;
			padding: 16rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 16rpx;
		}
	}
</style>